package com.efast.cafe.util;

import java.lang.reflect.Method;

/**
 * 反射机制代理类
 * 
 * @author Jony
 * 
 */
public class ReflactObject {

	private Object target; // 目标对象

	private String methodName; // 目标方法

	private Object[] params; // 参数数组

	private Method method;

	public ReflactObject() {
	}

	public Object getTarget() {
		return target;
	}

	public void setTarget(Object target) {
		this.target = target;
	}

	public String getMethodName() {
		return methodName;
	}

	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	public Object[] getParams() {
		return params;
	}

	public void setParams(Object[] params) {
		this.params = params;
	}

	public Method getMethod() {
		return method;
	}

	public void setMethod(Method method) {
		this.method = method;
	}

	/**
	 * 重新设置目标方法
	 */
	private void resetMethod(String methodName) {
		if (params != null) { // 目标方法有参数
			int paramsLength = params.length;
			Class<?>[] paramsTypes = new Class<?>[paramsLength];
			for (int i = 0; i < paramsLength; i++) {
				paramsTypes[i] = params[i].getClass();
			}
			try {
				method = target.getClass().getMethod(methodName, paramsTypes);
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		} else {// 目标方法参数为null
			try {
				method = target.getClass().getMethod(methodName, null);
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 重新设置目标对象和方法
	 */

	private void resetTarget(Object target, String methodName) {

		this.target = target;

		this.resetMethod(methodName);

	}

	/**
	 * 动态调用已绑定方法
	 */

	public Object doMethod() throws Exception {

		resetTarget(target, methodName);
		return this.method.invoke(target, params);
	}

}
